import { _decorator, Component, EventTouch, input, Input, Label, Node, UITransform, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

//虚拟摇杆管理器
@ccclass('JoyStickManager')
export class JoyStickManager extends Component {
    //实际移动的值，需要给外部使用
    input:Vec2 =Vec2.ZERO;

    private body: Node;
    private stick: Node;
    private defaultPos:Vec2;
    
    //记录轮盘半径
    private radius:number 
    init () {
        this.body=this.node.getChildByName('Body');
        this.stick =this.body.getChildByName('Stick');
        //记录轮盘初始位置
        this.defaultPos =new Vec2(this.body.position.x,this.body.position.y);
        this.radius =this.body.getComponent(UITransform).contentSize.x/2;
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);

    }

    onDestroy () {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchStart(e: EventTouch) {
        const touchPos = e.getUILocation();
        this.body.setPosition(touchPos.x, touchPos.y);
    }
    onTouchMove(e: EventTouch) {
        const touchPos = e.getUILocation();
        const stickPos = new Vec2(touchPos.x-this.body.position.x , touchPos.y-this.body.position.y); 
        //把值限制在摇杆半径内
        if (stickPos.length()>this.radius){
            stickPos.multiplyScalar(this.radius/stickPos.length());
        }
        this.stick.setPosition(stickPos.x, stickPos.y);
        //归一化会改变原坐标，所有要clone
        this.input = stickPos.clone().normalize();
        // console.log(this.input);
    }
    onTouchEnd() {
        this.body.setPosition(this.defaultPos.x, this.defaultPos.y);
        this.stick.setPosition(0, 0);
        this.input = Vec2.ZERO;
    }
    
    
}

